package com.eltsistemas.controller.setor;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.eltsistemas.controller.grupo.GrupoComPermissao;
import com.eltsistemas.dao.GenericDao;
import com.eltsistemas.hibernate.HibernateUtil;
import com.eltsistemas.modelo.Setor;
import com.eltsistemas.modelo.Usuario;

@Controller
@SessionAttributes("usuario_Logado")
public class SetorRemove {
	
	@RequestMapping(value="/setor/remover", method=RequestMethod.GET)
	public String remover(Setor setor, @ModelAttribute("usuario_Logado") Usuario user)
	{
		try
		{
			//Verifica as permissoes do grupo
			List<String> moduloList = new GrupoComPermissao().getPermissao(user.getGrupo(), "Setor");
			for(String modulo : moduloList)
			{
				if(modulo.equals("remover"))
				{
					Session session = new HibernateUtil().getSession();
					session.beginTransaction();
					
					GenericDao<Setor> daoSetor = new GenericDao<>(session, Setor.class);
					
					//Comita os dados
					session = daoSetor.remover(setor);
					session.beginTransaction().commit();
					session.close();
					return "redirect:lista";
				}
			}
			return "redirect:/painel/index";
		}
		catch(HibernateException e)
		{
			if(e.getClass().toString().contains("ConstraintViolationException"))
			{
				return "redirect:lista?valor=remove";
			}
			
			return "redirect:/painel/erro";
		}
	}

}
